<?php

declare(strict_types=1);

namespace app\common\service\crm;

use app\common\service\hrm\FilesService;
use app\common\traits\ServiceTrait;
use app\common\dao\crm\ProductTypeDao;

/**
 * 客户产品分类 服务业务层(Service)
 * @author 吕玉冰
 * @date  2022-07-20
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class ProductTypeService
{
    protected $dao = null;

    public function __construct()
    {
        $this->dao = new ProductTypeDao();
    }

    use ServiceTrait;


    public function _list_where($data)
    {
        $where = [];
        if (isset($data['keywords']) && !empty($data['keywords'])) {
            $where[] = ["name", "like", "%" . $data['keywords'] . "%"];
        }
        $data['where'] = $where;
        return [
            'where' => isset($data['where']) ? $data['where'] : [],
            'order' => isset($data['order']) ? $data['order'] : [],
            'field' => isset($data['field']) ? $data['field'] : ['*'],
        ];
    }

    /**
     * 重写 输出格式化
     */
    public function _list_format($list)
    {
        foreach ($list as $k => &$v) {
            if (isset($v['files_id'])) {
                $list[$k]['files_id'] = _img($v['files_id']);
            }
        }
        return $list;
    }


    /**
     * 保存表单数据
     * @param $data
     * @return array
     */
    public function saveForm($data)
    {
        if (empty($data)) {
            return _err(1002);
        }
        if (isset($data['id']) && !empty($data['id'])) {
            $result = $this->dao->update($data['id'], $data);
            if (isset($data['files_id'])) {
                (new FilesService())->add([
                    'table_name' => 'crm_product_type',
                    'table_id' => $data['id'],
                    'files_id' => $data['files_id']
                ]);
            }
            if ($result) {
                return _ok(1021);
            }
        } else {


            $result = $this->dao->add($data);
            if ($result) {
                $return = _ok(1023);
                if (!empty($result->id)) {
                    $return['data'] = $result->id;
                    if (isset($data['files_id'])) {
                        (new FilesService())->add([
                            'table_name' => 'crm_product_type',
                            'table_id' => $result->id,
                            'files_id' => $data['files_id']
                        ]);

                    }

                }
                return $return;
            }
        }
        return _err(1005);
    }
}
    